<template>
  <div
    id="layerControl_zw"
    class="data-table"
    @mousedown="mousedown"
    @click.stop = ""
    :style="'position:fixed;left:'+left+'px;top:'+top+'px;'">
    <div class="title">
      <span>选择底图</span>
      <i class="close el-icon-close" @click.stop="close"></i>
      <!-- <i class="close el-icon-zoom-in"></i> -->
    </div>
    <ul class="base-layer-layers">
      <li
        v-for="(item,index) in baseLayers"
        :key="index"
        @click.stop="switchLayer(item)"
        @mousedown="stopCapture"
      >
        <img
          :src="mapbg[index]"
          width="64px"
          :class="{'layer-status':item.curLayer}"
        />
        <div :class="{'text':true,'text-status':item.curLayer}">{{item.layerName}}</div>
      </li>
    </ul>
    <!-- 分割线-------------------分割线---------------分割线 -->
    <div style="padding:0 5px">
      <div class="other-title" @click.stop="overLayersListVisible=!overLayersListVisible">
        专题图
        <div class="other-title-btn">
          <i class="el-icon-arrow-right" v-if="!overLayersListVisible"></i>
          <i class="el-icon-arrow-down" v-if="overLayersListVisible"></i>
        </div>
      </div>
      <ul class="other-layer-layers" v-if="overLayersListVisible">
        <p class="title">聚集图</p>
        <el-collapse v-model="collapseactiveName" accordion @change="getChartItem(collapseactiveName,'clusterLayer')" size="mini">
          <el-collapse-item
          v-for="(item,index) in overLayerData.clusterLayer"
          v-if="item"
          :key="'clusterLayer-'+index"
          :title="item.name||''"
          :name="item.name||''"
          :disabled="item.hidden"
          >
          <template slot="title">
            {{item.name}}
            <span class="check-box">
              <!-- <i
                class="iconfont icon-shangyi overlayer-visible"
                v-show="item.data.data.length>0"
                @click.stop="setLayerUp(item,index,true)"
              ></i>
              <i
                class="iconfont icon-xiayi overlayer-visible"
                v-show="item.data.data.length>0"
                @click.stop="setLayerUp(item,index,false)"
              ></i> -->
              <i
                class="iconfont icon-yanjing overlayer-visible"
                @click.stop="setOverLayerHidden(item,index)"
                v-if="!item.hidden"
              ></i>
              <i
                class="iconfont icon-biyanjing overlayer-visible"
                @click.stop="setOverLayerVisible(item)"
                v-if="item.hidden"
              ></i>
            </span>
          </template>

            <el-select v-model="selectedIdenValue" placeholder="请选择指标" @change="updatePolyChartWhenIdenChange(item,selectedIdenValue)" size="mini">
              <el-option
                v-for="(iden,idenindex) in numIden"
                :key="idenindex"
                :label="iden.idenName"
                :value="iden.idenCode">
              </el-option>
            </el-select>

          </el-collapse-item>
        </el-collapse>


        <p class="title">麻点图</p>
        <li
          v-for="(item,index) in overLayerData.pockingLayer"
          v-if="item"
          :key="'pockingLayer-'+index"
          :class="{'is-selected-status':item.tryOpacity}"
        >
          {{item.name}}
          <span class="check-box">
            <!-- <i
              class="iconfont icon-shangyi overlayer-visible"
              v-show="item.data.data.length>0"
              @click.stop="setLayerUp(item,index,true)"
            ></i>
            <i
              class="iconfont icon-xiayi overlayer-visible"
              v-show="item.data.data.length>0"
              @click.stop="setLayerUp(item,index,false)"
            ></i> -->
            <i
              class="iconfont icon-yanjing overlayer-visible"
              @click.stop="setOverLayerHidden(item,index)"
              v-if="!item.hidden"
            ></i>
            <i
              class="iconfont icon-biyanjing overlayer-visible"
              @click.stop="setOverLayerVisible(item)"
              v-if="item.hidden"
            ></i>
          </span>
        </li>
        <p class="title">热力图</p>
        <el-collapse v-model="collapseactiveName" accordion @change="getChartItem(collapseactiveName,'heatLayer')" size="mini">
          <el-collapse-item
          v-for="(item,index) in overLayerData.heatLayer"
          v-if="item"
          :key="'heatLayer-'+index"
          :title="item.name||''"
          :name="item.name||''"
          :disabled="item.hidden"
          >
          <template slot="title">
            {{item.name}}
            <span class="check-box">
              <!-- <i
                class="iconfont icon-shangyi overlayer-visible"
                v-show="item.data.data.length>0"
                @click.stop="setLayerUp(item,index,true)"
              ></i>
              <i
                class="iconfont icon-xiayi overlayer-visible"
                v-show="item.data.data.length>0"
                @click.stop="setLayerUp(item,index,false)"
              ></i> -->
              <i
                class="iconfont icon-yanjing overlayer-visible"
                @click.stop="setOverLayerHidden(item,index)"
                v-if="!item.hidden"
              ></i>
              <i
                class="iconfont icon-biyanjing overlayer-visible"
                @click.stop="setOverLayerVisible(item)"
                v-if="item.hidden"
              ></i>
            </span>
          </template>

            <el-select v-model="selectedIdenValue" placeholder="请选择指标" @change="updatePolyChartWhenIdenChange(item,selectedIdenValue)" size="mini">
              <el-option
                v-for="(iden,idenindex) in numIden"
                :key="idenindex"
                :label="iden.idenName"
                :value="iden.idenCode">
              </el-option>
            </el-select>

          </el-collapse-item>
        </el-collapse>
      </ul>



    </div>
    <!-- 分割线-------------------分割线---------------分割线 -->
    <!-- <div @mousedown="stopCapture" style="padding:0 5px">
      <div class="other-title line-top" @click="opacitySliderVisible=!opacitySliderVisible">
        透明度
        <div class="other-title-btn">
          <i class="el-icon-arrow-right" v-if="!opacitySliderVisible"></i>
          <i class="el-icon-arrow-down" v-if="opacitySliderVisible"></i>
        </div>
      </div>
      <div class="other-layer-layers" style="padding:0 18px 0px 10px" v-if="opacitySliderVisible">
        <el-slider
          v-model="layersOpacity"
          :max="100"
          :min="0"
          :step="1"
          @change="setOverLayersOpacity"
          @mousedown="stopCapture"
        ></el-slider>
      </div>
    </div> -->


  </div>
</template>

<script>
import sgisLayerBase from "@/utils/map/sfgis.layer.base.js";
import sgisMapBase from "@/utils/map/sfgis.map.base.js";
import sgisRegionBase from "@/utils/map/sfgis.region.base.js";
import mapTool from "@/utils/map/sfgis.map.tool.js";
import Layer from "@/utils/map/lib/main.js"; // 专题图层绘画函数
import styleModify from '@/utils/map/lib/macrolayers/echarts.stylemodify.js';
import regionLable from "@/utils/map/lib/systemlayers/region.marker.layer";
import { setTimeout } from "timers";
import searchresultData from "../query/searchresult.data.js"; //处理专题图数据格式
import axios from "axios";
import * as microAPI from "@/pages/micro/api/micro.js";
import microConfig from "static/config/micro.js";
export default {
  name: "Layers",
  props: [],
  data() {
    return {
      baseLayers: sgisLayerBase.baseLayers,
      overLayersListVisible: false, // 专题图层列表可见性
      overLayers: sgisLayerBase.overLayers, // 获取当前的overLayers个数
      overLayerChangeByCurControl: false, // 记录专题专题图层个数变更原因
      opacitySliderVisible: false, // 透明度滑块是否可见
      layersOpacity: 100, // 专题图层透明度
      otherLegends: [],
      currentLayer: "",

      status: {
        isdblclick:false,//是否是双击下钻
        pylevel:microConfig.pylevel,//聚集等级
        isFirstMicroSearch: true, //是否是第一次查询麻点图
        chartType:"clusterLayer", //图形类型
        saveOpenChart:[]
      },
      left: document.documentElement.clientWidth - 420,
      top: 250,
      map: {
        currentZoom: 4 //地图当前等级
      }, //当前地图
      chartIndex:0,
      microSearchParams:[],//查询结果所有条件
      selectedSearchParams:{},//当前选中结果条件
      overLayerData:{
        clusterLayer:[],
        pockingLayer:[],
        heatLayer:[]
      },
      //数字指标
      numIden:[{
        value: '单位数量',
        label: ''
      }],
      selectedIdenValue:"",//选中指标值
      handle:{
        item:{},//操作的目标结果
      },
      collapseactiveName: '',//折叠面板打开层
      mapbg:["static/images/map-bg/map-bg-1.png","static/images/map-bg/map-bg-2.png","static/images/map-bg/map-bg-3.png"]//底图背景
    };
  },
  watch: {
    layersOpacity(now_opcity, old_opcity) {}
  },
  mounted() {
    EventBus.$on("updateMarkChartData", this.updateMarkChartData);
    EventBus.$on("highLightMarker", this.highLightMarker);
    EventBus.$on("updateMicroSearch", this.updateMicroSearch);
    EventBus.$on("clearMicroAllChart", this.clearMicroAllChart);
    EventBus.$on("closeAllChart", this.closeAllChart);
    EventBus.$on("addRegionLablesComplete", this.addRegionLablesComplete);
    EventBus.$on("refreshBoundaryFeaturesComplete", this.refreshBoundaryFeaturesComplete);
  },
  beforeDestroy() {
    EventBus.$off("updateMarkChartData", this.updateMarkChartData);
    EventBus.$off("highLightMarker", this.highLightMarker);
    EventBus.$off("updateMicroSearch", this.updateMicroSearch);
    EventBus.$off("clearMicroAllChart", this.clearMicroAllChart);
    EventBus.$off("closeAllChart", this.closeAllChart);
    EventBus.$off("addRegionLablesComplete", this.addRegionLablesComplete);
    EventBus.$off("refreshBoundaryFeaturesComplete", this.refreshBoundaryFeaturesComplete);
  },
  methods: {
    //更新区划等级
    updateRegionsPylevel(selectedSearchParams) {
      let that = this;
      if(selectedSearchParams.hasOwnProperty("microid")){//有数据
        let len = selectedSearchParams.regions.regionArr.length;
        let regionCode = selectedSearchParams.regions.regionArr[0].regionCode;
        let level = that.status.pylevel;
        level = sgisRegionBase.regionUtils.getRegionLevel(regionCode);

        if(len == 1){
          that.status.pylevel = level+1;//默认查询区划下一级
        }else if (len > 1){
          that.status.pylevel = level;//默认查询区划当前级别
        }

      }

    },
    //关闭所有图表
    closeAllChart(){
      let that = this;
      for(let type in this.overLayerData){
        let arr = this.overLayerData[type];
        for(let i in arr){
          that.setOverLayerHidden(arr[i],i);
        }
      }
    },
    mousedown(e) {
      if (e.srcElement.className == "title") {
        document.onmousemove = e2 => {
          this.left = e2.clientX - e.offsetX;
          this.top = e2.clientY - e.offsetY;
        };
        document.onmouseup = () => {
          document.onmousemove = null;
          document.onmousedown = null;
        };
      }
    },
    closeInfoWin() {
      this.changeShowDataTable(!this.showDataTable);
    },
    //区划标签添加完成
    addRegionLablesComplete(){
      if(this.selectedSearchParams.hasOwnProperty("microid")){
        //隐藏标签
        let className = ".region-lable-" + sgisMapBase.map._container.id;
        let label = $(className);
        if(label.length>0){
          $(className).hide();
        }
      }
    },
    // 区划边界平滑缩放完成
    refreshBoundaryFeaturesComplete(){
      let that = this;
      if(that.status.chartType!="pockingLayer"){
        setTimeout(function(){//延时监听地图缩放，防止重复查询
          that.status.isdblclick = false;//打开缩放功能
           const map = sgisMapBase.getMap();
           let zoom = Math.round(map.getZoom());
           that.map.currentZoom = zoom;//重置地图等级
        },microConfig.openZoomEndTime)
      }
    },
    //更新基层查询结果条件
    updateMicroSearch(microSearchParams,selectedSearchParams,type){
      let that = this;
      if(type=="upOrDownDirr"){//下钻
        let chartType = this.status.chartType;
        let arr = this.overLayerData[chartType];
        that.status.saveOpenChart = [];
        for(let j in arr){
          let item = arr[j];
          if(!item.hidden){//目前打开的专题图
            that.status.saveOpenChart.push(item.sort);
          }
        }
        that.status.isdblclick = true;//不监听地图放大缩小事件
      }
      if(type!="upOrDownDirr"){
        that.status.saveOpenChart = [];

      }
      that.clearMicroAllChart();
      //转换防止继承上次数据
      let searchParams_str = JSON.stringify(microSearchParams);
      let searchParams_parse = JSON.parse(searchParams_str);
      let selectedParams_str = JSON.stringify(selectedSearchParams);
      let selectedParams_parse = JSON.parse(selectedParams_str);
      that.microSearchParams = searchParams_parse;
      that.selectedSearchParams = selectedParams_parse;

      that.updateRegionsPylevel(that.selectedSearchParams);
      for(let i =0; i < that.microSearchParams.length; i++){
          let item = that.microSearchParams[i];
          let pockingChartData = [
              {
                  type: 'pockingLayer',
                  name: item.title+'-麻点图',
                  sort:item.sort,
                  data: {
                      id: "2_"+item.sort,
                      name: item.title+"-麻点图",
                      data: []
                  }
              }
          ];
          let clusterChartData = [
              {
                  type: 'clusterLayer',
                  name:item.title+"-聚集图",
                  sort:item.sort,
                  data: {
                      id: "3_"+item.sort,
                      name: item.title+"-聚集图",
                      data: []
                  }
              }
          ];
          let heatChartData = [
              {
                  type: 'heatLayer',
                  name: item.title+'-热力图',
                  sort:item.sort,
                  data: {
                      id: "4"+item.sort,
                      name: item.title+"-热力图",
                      data: []
                  }
              }
          ];
          that.initChart(clusterChartData);
          that.initChart(pockingChartData);
          that.initChart(heatChartData);
      }

    },
    //聚集图查询
    polymerizationSearch(args,callback) {
      let that = this;
      axios({
        url: microConfig.polymerSearch,
        method: "post",
        timeout: axiosTimeOut,
        params: {
          idenCode:args.idenCode||'',
          microId: args.microId,
          rcid: args.rcid,
          regionlevel: that.status.pylevel
        },
        data: args.microQuery
      })
        .then(function(response) {
          if (response.data.message == "success") {
            let data = response.data.data;
            if (data.length > 0) {
                callback(data);
            }else{
              // that.status.isdblclick = false;//打开缩放功能
            }
          } else {
            that.$message({
              message: response.data.message,
              type: "error"
            });
            return;
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //麻点图数据查询
    pockingSearch(args,callback) {
      let that = this;
      axios({
        url: microConfig.pockingSearch,
        method: "post",
        timeout: axiosTimeOut,
        params: {
          microId: args.microId
        },
        data: args.microQuery
      })
        .then(function(response) {
          if (response.data.message == "success") {
            let data = response.data.data;
            if (data.length > 0) {
              //用全局事件总线去更新麻点图
              callback(data);
            }
          } else {
            that.$message({
              message: response.data.message,
              type: "error"
            });
            return;
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //上下移
    setLayerUp(item, index, isUp) {
      let type = item.type;
      if (isUp) {//上移
        if (index === 0) {
          return;
        }
        this.overLayerData[type].splice(index - 1, 0, item);
        this.overLayerData[type].splice(index + 1, 1);
        const chartLayer = sgisMapBase.map.overlayers[item.layerId];
        chartLayer.setZIndexOffsetHasGroup(1,item.layerId,item.type);
      } else {//下移
        if (index === this.overLayerData[type].length - 1) {
          return;
        }
        this.overLayerData[type].splice(index, 1);
        this.overLayerData[type].splice(index + 1, 0, item);
         const chartLayer = sgisMapBase.map.overlayers[item.layerId];
        chartLayer.setZIndexOffsetHasGroup(1,item.layerId,item.type);
      }
    },
    setOverLayersOpacity() {
      const opacity = this.layersOpacity / 100;
      if (this.currentLayer) {
        if (this.currentLayer.layer["charts"]) {
          this.currentLayer.layer["charts"].forEach(layerItem => {
            layerItem.echart._dom.style.opacity = opacity;
          });
        } else {
          if (this.currentLayer.layer instanceof Array) {
            this.currentLayer.layer[0]._container.style.opacity = opacity;
          } else if(this.currentLayer.layer.rootCanvas){
            this.currentLayer.layer.rootCanvas.style.opacity = opacity;
          }else{
            this.currentLayer.layer.canvas.style.opacity = opacity;
          }
        }
      }
    },
    setSelectedStatus(el, item, index) {
      this.overLayerData.forEach(item => {
        item.tryOpacity = false;
      });
      // 设置那条数据可以设置透明度属性
      item.tryOpacity = true;
      this.$set(this.overLayerData, index, item);
      this.overLayers.forEach(layer_item => {
        if (item.layerId == layer_item.layerId && !layer_item.hidden) {
          this.currentLayer = layer_item;
        }
      });
    },
    //展示专题图
    setOverLayerVisible(item,index) {
      let that = this;
      const layerInfo = sgisMapBase.map.overlayerInfos[item.layerId];
      const layer = sgisMapBase.map.overlayers[item.layerId];
      item.hidden = false;

      if(!layer){//该专题图层不存在
          let param ={};
          for(let i = 0 ; i < that.microSearchParams.length; i++){
            if( that.microSearchParams[i].sort == item.sort){
              param = that.microSearchParams[i];
            }
          }
          let microQuery = {
              conditions: param.conditions,
              msConditions: param.msConditions,
              isSpecial: "none", //直接如此传
              periods: param.periods,
              regionType: param.regions.regionCodeType,
              regions: param.regions.regionArr
          };
          let args = {
            current: param.pagenum,
            size: microConfig.table.pagesize,
            microId: param.microid, //主表id
            microQuery: microQuery,
            rcid: param.regions.rcid,
            regions: param.regions.regionArr,
            idenCode:param.idenCode||''
          };
        if(item.type == "clusterLayer"){//聚集图打开

          that.polymerizationSearch(args,function(dataobj){
              that.checkIsOnlyIden(param.conditions,function(imageUrl){
                that.renderPolyChart(dataobj,item,param.idenObj,imageUrl)
                const chartLayerInfo = sgisMapBase.map.overlayerInfos[item.layerId];
                const chartLayer = sgisMapBase.map.overlayers[item.layerId];
                chartLayer.setVisible("visible",sgisMapBase.map,chartLayer);
                chartLayer.setOpacity(1,sgisMapBase.map,chartLayer);
                that.otherLegends.push(chartLayerInfo);
                that.$emit("getOtherLegendVisible", that.otherLegends);
                that.overLayerData[item.type][item.sort].data.data = dataobj;
                that.overLayerData[item.type][item.sort].pylevel = that.status.pylevel;//存入本次查询等级

                that.zoomendfunc();

              })
          })
        }
        if(item.type == "pockingLayer"){//麻点图打开
          that.pockingSearch(args,function(dataobj){
              that.renderPockingChartData(dataobj,item)
              const chartLayerInfo = sgisMapBase.map.overlayerInfos[item.layerId];
              const chartLayer = sgisMapBase.map.overlayers[item.layerId];
              chartLayer.setVisible("visible",sgisMapBase.map,chartLayer);
              chartLayer.setOpacity(1,sgisMapBase.map,chartLayer);
              that.otherLegends.push(chartLayerInfo);
              that.$emit("getOtherLegendVisible", that.otherLegends);
              that.overLayerData[item.type][item.sort].data.data = dataobj;
          })
        }
        if(item.type == "heatLayer"){//热力图

          that.polymerizationSearch(args,function(dataobj){
              that.renderHeatChart(dataobj,item)
              const chartLayerInfo = sgisMapBase.map.overlayerInfos[item.layerId];
              const chartLayer = sgisMapBase.map.overlayers[item.layerId];
              chartLayer.setVisible("visible",sgisMapBase.map,chartLayer);
              chartLayer.setOpacity(1,sgisMapBase.map,chartLayer);
              that.otherLegends.push(chartLayerInfo);
              that.$emit("getOtherLegendVisible", that.otherLegends);
              that.overLayerData[item.type][item.sort].data.data = dataobj;
              that.overLayerData[item.type][item.sort].pylevel = that.status.pylevel;//存入本次查询等级

              that.zoomendfunc();

          })
        }
      }else{//图层存在
        layer.setVisible("visible",sgisMapBase.map,layer);
        layer.setOpacity(1,sgisMapBase.map,layer);
        that.otherLegends.push(layerInfo);
        that.$emit("getOtherLegendVisible", that.otherLegends);

        let aim=null;
        if(that.overLayerData[item.type].length>0){
          aim = that.overLayerData[item.type][item.sort];
        }

        let aimpylevel=that.status.pylevel;
        if(aim){
          if(aim.hasOwnProperty("pylevel")){
            aimpylevel = aim.pylevel;
          }
        }
        if(aimpylevel!=that.status.pylevel&&item.type != "pockingLayer"){//上次查询等级与当前等级不一致，更新该专题图
          that.updateAimPolyChart(aim);
        }
      }
      this.$set(this.overLayerData[item.type], item.sort, item);

      that.status.chartType = item.type;
      for(let type in this.overLayerData){
        if(type!=this.status.chartType){//其他类型专题图关闭
          let arr = this.overLayerData[type];
          for(let i in arr){
            that.setOverLayerHidden(arr[i],i);
          }
        }
      }

      //marker只与麻点图同时出现
      const map = sgisMapBase.getMap();
      regionLable.hideLayer(map);

      if(this.status.chartType=="pockingLayer"){//麻点图
        Layer["markerLayer"].showLayer(map);
      }else{
        Layer["markerLayer"].hideLayer(map);
        Layer["markerLayer"].clearHoverMarker();
        Layer["markerLayer"].clearPopup();
      }
    },
    //隐藏专题图
    setOverLayerHidden(item,index) {
      let that = this;
      const layerInfo = sgisMapBase.map.overlayerInfos[item.layerId];
      const layer = sgisMapBase.map.overlayers[item.layerId];
      if(layer){//该图层已经渲染过
        item.hidden = true;
        layer.setVisible("hidden",sgisMapBase.map,layer);
        layer.setOpacity(1,sgisMapBase.map,layer);
        for (const key in that.otherLegends) {
          const item = that.otherLegends[key];
          if (item.layerId === layerInfo.layerId) {
            that.otherLegends.splice(key, 1);
            break;
          }
        }
        that.$emit("getOtherLegendHidden", that.otherLegends);
      }
      that.$set(that.overLayerData[item.type], item.sort, item);
      // if(index!=undefined&&index!=""){
      //   this.$set(this.overLayerData[item.type], index, item);
      // }else{
      //   this.$set(this.overLayerData[item.type], this.overLayerData[item.type].length, item);
      // }

      that.collapseactiveName = "";//关闭折叠面板

    },
    //切换底图
    switchLayer(item) {
      for (const key in this.baseLayers) {
        this.baseLayers[key].curLayer = false;
        this.$set(this.baseLayers, key, this.baseLayers[key]);
        if (item.layerId === this.baseLayers[key].layerId) {
          this.baseLayers[key].curLayer = true;
          this.$set(this.baseLayers, key, this.baseLayers[key]);
        }
      }
      sgisLayerBase.switchBaseLayer(item.layerId);
    },
    //关闭面板
    close() {
      this.$emit("close");
    },
    //移动结束
    stopCapture(e) {
      e.stopPropagation();
      e.stopImmediatePropagation();
    },
    //移动面板
    move(e) {
      // let odiv = e.target; //获取目标元素
      e.stopPropagation();
      e.stopImmediatePropagation();
      const odiv = document.getElementById("layerControl_zw");
      // 算出鼠标相对元素的位置
      const disX = e.clientX - odiv.offsetLeft;
      const disY = e.clientY - odiv.offsetTop;
      document.onmousemove = e => {
        // 鼠标按下并移动的事件
        // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        const left = e.clientX - disX;
        const top = e.clientY - disY;

        // 绑定元素位置到positionX和positionY上面
        this.positionX = top;
        this.positionY = left;

        // 移动当前元素
        odiv.style.position = "absolute";
        odiv.style.left = left + "px";
        odiv.style.top = top + "px";
      };
      document.onmouseup = e => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    },

    //更新Marker图
    updateMarkChartData(markerData, pockingLayerLarge) {
      let that = this;
      let markdata = [];
      if (markerData.hasOwnProperty("TYPE")) {
        // markdata = searchresultData.initPockingData_ESSearch(markerData);
      } else {
        markdata = searchresultData.initMarkerData(markerData);
      }
      let dataobj = {
        id: "1",
        symbol: "pin",
        color: "red",
        name: "Marker图",
        symbolSize: 45,
        datas: markdata
      };
      let updateChartData = [
        {
          type: "markerLayer",
          name: "Marker图",
          data: dataobj,
          class: "markerLayer"
        }
      ];
      that.initChart(updateChartData);
    },
    //绘制专题图
    initChart(chartData) {
      let that = this;
      for (const key in chartData) {
        const item = chartData[key];
        const type = item.type;
        const map = sgisMapBase.getMap();
        const data = item.data ? item.data : item.datas;
        if (type == "markerLayer") {
          //去绘制Mark点
          const layerInfo = Layer[type].createLayer(map, data);
          if(this.status.chartType!="pockingLayer"){
            Layer["markerLayer"].hideLayer(map);
            Layer["markerLayer"].clearHoverMarker();
            Layer["markerLayer"].clearPopup();
          }
        } else if (that.status.chartType == item.type) {//当前展示图形类型一致
          if(that.status.saveOpenChart.length>0){//区划更新展示上次记录图
            if(that.status.saveOpenChart.includes(item.sort)){
              const layerInfo = Layer[type].initLayer(map,data);
              item.layerId = layerInfo.layerId;
              item.hidden = true;
              that.setOverLayerVisible(item);
            }else{
              const layerInfo = Layer[type].initLayer(map, data);
              item.layerId = layerInfo.layerId;
              item.hidden = true;
              that.setOverLayerHidden(item);
            }
          }else if(this.selectedSearchParams.sort==item.sort){//展示选中图
            const layerInfo = Layer[type].initLayer(map,data);
            item.layerId = layerInfo.layerId;
            item.hidden = true;
            that.setOverLayerVisible(item);
          }else{
            const layerInfo = Layer[type].initLayer(map, data);
            item.layerId = layerInfo.layerId;
            item.hidden = true;
            that.setOverLayerHidden(item);
          }
        }else {
          const layerInfo = Layer[type].initLayer(map, data);
          item.layerId = layerInfo.layerId;
          item.hidden = true;
          that.setOverLayerHidden(item);
        }
        if((that.status.chartType=="clusterLayer"||that.status.chartType=="heatLayer")&&that.microSearchParams.length>0){
          that.zoomendfunc();
        }
      }
    },
    //高亮marker图
    highLightMarker(id,type) {
      if(type=="hover"){
        Layer.markerLayer.createHoverMarker(id);
      }else if(type=="click"){
        Layer.markerLayer.highLightMarker(id);
      }else if(type=="leave"){
        Layer.markerLayer.clearHoverMarker();
      }else if(type=="position"){//定位
        Layer.markerLayer.createHoverMarkerByData(id);
      }
    },
    //绘制聚集图
    renderPolyChart(polydata,item,field,imageUrl){
      let pockdataobj = searchresultData.initPolyData(polydata,field);
      let dataobj = {
        id: "3_"+item.sort,
        name: item.name,
        data: pockdataobj
      };
      const map = sgisMapBase.getMap();
      Layer["clusterLayer"].renderLayer(map,dataobj,item,imageUrl);
    },
    //绘制热力图
    renderHeatChart(data,item,field){
      let pockdataobj = searchresultData.initHeatData(data,field);
      let dataobj = {
        id: "4_"+item.sort,
        name: item.name,
        data: pockdataobj
      };
      const map = sgisMapBase.getMap();
      Layer["heatLayer"].renderLayer(map,dataobj,item);
    },
    //绘制麻点图
    renderPockingChartData(pockingdata,item){
      let pockdataobj = searchresultData.initPockingData(pockingdata);
      let dataobj = {
        id: "2_"+item.sort,
        name: item.name,
        data: pockdataobj
      };
      const map = sgisMapBase.getMap();
      Layer["pockingLayer"].renderLayer(map,dataobj,item);
    },
    //清除所有专题图层
    clearMicroAllChart(callback){
      let that = this;
      that.microSearchParams = [];
      that.selectedSearchParams = {};
      let overLayers = sgisLayerBase.getOverLayers();
      let len = overLayers.length;

      for(let i = (len-1); i>-1 ; i--){
        const type = overLayers[i].type;
        sgisLayerBase.removeOverLayer(overLayers[i].layerId);
        that.overLayerData[type].splice(i, 1);
      }

      let map = sgisMapBase.getMap();
      //清除marker及信息框
      Layer.markerLayer.clearAll();

      //清除图例
      that.otherLegends=[];
      this.$emit("getOtherLegendHidden", this.otherLegends);

      this.status.isFirstMicroSearch = true;

      //清空各专题图层默认顺序，防止重新绘制专题图失效
      styleModify.clearLayerOrderHasGroup();

      //清空专题图列表
      this.overLayerData.clusterLayer = [];
      this.overLayerData.pockingLayer = [];
      this.overLayerData.heatLayer = [];

      //清空数字指标
      this.numIden = [];
      this.selectedIdenValue = "";
      this.collapseactiveName = "";

      callback&&callback();
    },
    //判断下钻或缩放
    zoomendfunc(e) {
      let that = this;
      const map = sgisMapBase.getMap();
      map.off("zoomend").on("zoomend", function(){
        if(!that.status.isdblclick){//不是区划变更
          let zoom = Math.round(map.getZoom());
          that.gotozoomfunc(zoom);
        }
      });
    },
    //地图缩放
    gotozoomfunc(_zoom) {
      let that = this;
      if (_zoom == that.map.currentZoom) {
        return;
      } else{
        if ((that.status.chartType=="clusterLayer"||that.status.chartType=="heatLayer")&&that.microSearchParams.length>0) {//聚集图、热力图显示才上下钻
          const map = sgisMapBase.getMap();
          const maplevel = _zoom;
          let parentsRegion = sgisRegionBase.regionUtils.getRegionCodeByLevelAndCode(
            that.selectedSearchParams.regions.regionArr[0].regionCode,
            maplevel
          );
          let newpylevel = parentsRegion.level + 1;
          //更新聚集图等级
          if (that.status.pylevel != newpylevel&&!(newpylevel<that.selectedSearchParams.regions.regionArr[0].regionLevel)) {//等级不能超过选中区划等级
            that.status.pylevel = newpylevel;
            if(!that.status.isdblclick){
              that.updatePolyChart();
            }
          }
        }
        that.map.currentZoom = _zoom;//重置地图等级
      }
    },
    //更新所有打开专题图
    updatePolyChart(){
      let that = this;
      let chartType = this.status.chartType;
      let arr = this.overLayerData[chartType];
      for(let j in arr){
        let item = arr[j];
        if(!item.hidden){//目前打开的专题图
          that.updateAimPolyChart(item);
        }
      }
    },
    //更新选中目标专题图
    updateAimPolyChart(item){
      let that = this;
      let layer = sgisMapBase.map.overlayers[item.layerId];
      let overLayers = sgisLayerBase.getOverLayers();//清空图层
      sgisLayerBase.removeOverLayer(item.layerId);
      for (const key in that.otherLegends) {//先移除图例
        if (item.layerId === that.otherLegends[key].layerId) {
          that.otherLegends.splice(key, 1);
          break;
        }
      }

      let param ={};
      for(let i = 0 ; i < that.microSearchParams.length; i++){
        if( that.microSearchParams[i].sort == item.sort){
          param = that.microSearchParams[i];
        }
      }
      let microQuery = {
          conditions: param.conditions,
          msConditions: param.msConditions,
          isSpecial: "none", //直接如此传
          periods: param.periods,
          regionType: param.regions.regionCodeType,
          regions: param.regions.regionArr
      };
      let args = {
        current: param.pagenum,
        size: microConfig.table.pagesize,
        microId: param.microid, //主表id
        microQuery: microQuery,
        rcid: param.regions.rcid,
        regions: param.regions.regionArr,
        idenCode:param.idenCode
      };
      if(item.type == "clusterLayer"){//聚集图打开
        that.polymerizationSearch(args,function(dataobj){
          that.checkIsOnlyIden(param.conditions,function(imageUrl){
            that.renderPolyChart(dataobj,item,param.idenObj,imageUrl)

            const chartLayerInfo = sgisMapBase.map.overlayerInfos[item.layerId];
            const chartLayer = sgisMapBase.map.overlayers[item.layerId];
            chartLayer.setVisible("visible",sgisMapBase.map,chartLayer);
            chartLayer.setOpacity(1,sgisMapBase.map,chartLayer);
            that.otherLegends.push(chartLayerInfo);
            that.$emit("getOtherLegendVisible", that.otherLegends);
            that.overLayerData[item.type][item.sort].data.data = dataobj;
            that.overLayerData[item.type][item.sort].pylevel = that.status.pylevel;//存入本次查询等级
          })
        })
      }
      if(item.type == "heatLayer"){//热力图
        that.polymerizationSearch(args,function(dataobj){
            that.renderHeatChart(dataobj,item)
            const chartLayerInfo = sgisMapBase.map.overlayerInfos[item.layerId];
            const chartLayer = sgisMapBase.map.overlayers[item.layerId];
            chartLayer.setVisible("visible",sgisMapBase.map,chartLayer);
            chartLayer.setOpacity(1,sgisMapBase.map,chartLayer);
            that.otherLegends.push(chartLayerInfo);
            that.$emit("getOtherLegendVisible", that.otherLegends);
            that.overLayerData[item.type][item.sort].data.data = dataobj;
            that.overLayerData[item.type][item.sort].pylevel = that.status.pylevel;//存入本次查询等级
        })
      }

    },
    //判断是否是单分组单分组值，是返回图片地址，否则返回false
    checkIsOnlyIden(conditions,callback){
      let that = this;
      let sum = 0;
      let index = '';
      let imageUrl = "";//图片地址
      for(let i in conditions){
        if(conditions[i].groupId){
          sum++;
          index = i;
        }
      }
      if(sum == 1){//只有一个分组
        let value = conditions[index].value;
        if(value.indexOf(",")==-1){//只有一个分组值
          let name = conditions[index].idenAliasCode+"-"+conditions[index].value;
          imageUrl=microConfig.imageUrl+name+".png";
        }
      }
      that.checkImgExists(imageUrl,function(){
        callback(imageUrl)
      },function(){
        callback(false)
      });
    },
    //判断图片是否存在
    checkImgExists(imgurl,success,err) {
      var ImgObj = new Image(); //判断图片是否存在
      ImgObj.onload=function(){
          success && success()
      }
      ImgObj.onerror=function(){
          err && err()
      }
      ImgObj.src = imgurl;
    },
    //更新聚集图指标
    updatePolyChartWhenIdenChange(item,selectedIdenValue){
      let that = this;
      item.selectedIdenValue = selectedIdenValue ;
      let idenObj = {};//选中的指标对象
      for(let i in item.numIden){
        if(item.selectedIdenValue == item.numIden[i].idenCode){
          idenObj = item.numIden[i];
        }
      }
      for (const key in that.otherLegends) {//先移除图例
        if (item.layerId === that.otherLegends[key].layerId) {
          that.otherLegends.splice(key, 1);
          break;
        }
      }
      let overLayers = sgisLayerBase.getOverLayers();//清空图层
      sgisLayerBase.removeOverLayer(item.layerId);

      let param ={};
      for(let i = 0 ; i < that.microSearchParams.length; i++){
        if( that.microSearchParams[i].sort == item.sort){
          param = that.microSearchParams[i];
          that.microSearchParams[i].idenCode = item.selectedIdenValue;//数字指标
          that.microSearchParams[i].idenObj = idenObj;//数字指标对象
        }
      }
      let microQuery = {
          conditions: param.conditions,
          msConditions: param.msConditions,
          isSpecial: "none", //直接如此传
          periods: param.periods,
          regionType: param.regions.regionCodeType,
          regions: param.regions.regionArr
      };
      let args = {
        microId: param.microid, //主表id
        microQuery: microQuery,
        rcid: param.regions.rcid,
        idenCode:item.selectedIdenValue
      };

      if(item.type=="clusterLayer"){//聚集图
        that.polymerizationSearch(args,function(dataobj){
          that.checkIsOnlyIden(param.conditions,function(imageUrl){
            that.renderPolyChart(dataobj,item,idenObj,imageUrl)//数字指标取值字段不一样
            const chartLayerInfo = sgisMapBase.map.overlayerInfos[item.layerId];
            const chartLayer = sgisMapBase.map.overlayers[item.layerId];
            chartLayer.setVisible("visible",sgisMapBase.map,chartLayer);
            chartLayer.setOpacity(1,sgisMapBase.map,chartLayer);
            that.otherLegends.push(chartLayerInfo);
            that.$emit("getOtherLegendVisible", that.otherLegends);
            that.overLayerData[item.type][item.sort].data.data = dataobj;
          })
        })
      }
      if(item.type=="heatLayer"){//热力图
        that.polymerizationSearch(args,function(dataobj){
          that.renderHeatChart(dataobj,item,idenObj)//数字指标取值字段不一样
          const chartLayerInfo = sgisMapBase.map.overlayerInfos[item.layerId];
          const chartLayer = sgisMapBase.map.overlayers[item.layerId];
          chartLayer.setVisible("visible",sgisMapBase.map,chartLayer);
          chartLayer.setOpacity(1,sgisMapBase.map,chartLayer);
          that.otherLegends.push(chartLayerInfo);
          that.$emit("getOtherLegendVisible", that.otherLegends);
          that.overLayerData[item.type][item.sort].data.data = dataobj;
        })
      }

    },
    getChartItem(activeName,chartType){
      let that = this;
      let item ={};
      if(chartType == "clusterLayer"){
        let arr = that.overLayerData["clusterLayer"];
        for(let i in arr){
          if(arr[i].name == activeName){
            item = arr[i];
          }
        };
      }
      if(chartType == "heatLayer"){
        let arr = that.overLayerData["heatLayer"];
        for(let i in arr){
          if(arr[i].name == activeName){
            item = arr[i];
          }
        };
      }
      that.getMicroIden(item);
    },
    //查询基层指标
    getMicroIden(item) {
      let that = this;
      if(!item.hidden){//该结果已打开
        that.handle.item = item;
        if(item.hasOwnProperty("numIden")){//该结果已经查询过数字指标
          let index = '';
          for(let i in that.microSearchParams){
            if(item.sort==that.microSearchParams[i].sort){
              index = i;
            }
          }
          that.numIden = that.overLayerData[item.type][index].numIden;
          that.selectedIdenValue = that.overLayerData[item.type][index].selectedIdenValue;
        }else{//还没有查询过指标
          let miid = '';
          let index = '';
          for(let i in that.microSearchParams){
            if(item.sort==that.microSearchParams[i].sort){
              miid = that.microSearchParams[i].microid;
              index = i;
            }
          }
          let req = {
            miid: miid,
            iden_type: ""
          };
          microAPI
            .getSelectedTableIden(req)
            .then(res => {
              if (res.message == "success" && res.data.length > 0) {
                let data = res.data;
                let numIden = [{
                  "idenName":"单位数量",
                  "idenCode":""
                }];
                for (let i in data) {
                  if (data[i].idenType == 2) {
                    //数字指标
                    numIden.push(data[i])
                  }
                }
                that.overLayerData[item.type][index].numIden = numIden;
                that.overLayerData[item.type][index].selectedIdenValue = numIden[0].idenCode;
                that.numIden = that.overLayerData[item.type][index].numIden;
                that.selectedIdenValue = that.overLayerData[item.type][index].selectedIdenValue;
              }
            })
            .catch(error => {
              console.log(error);
            });
        }
      }
    },
  }

};
</script>

<style rel='stylesheet' lang='scss' scoped>
@import "./../css/rule.scss";
$activeColor: #fff;
#layerControl_zw{
  background: $panelContentBg;
  .title{
    background: $panelTitleBg;
    color:$fontColor;
  }
  .base-layer-layers{
    .text{
      color:$fontColorLimit;
    }
  }
  .other-title{
    color:$fontColorLimit;
  }
}
.data-table {
  position: absolute;
  top: 250px;
  /*right: 46px;*/
  width: 360px;
  height: 300px;
  font-size: 1.4rem;
  z-index: 9999;
  background: $fontColorW;
  -webkit-box-shadow: 2px 5px 5px rgba(0, 0, 0, 0.3);
  box-shadow: 2px 5px 5px rgba(0, 0, 0, 0.3);
  .title {
    height: 35px;
    background: $backGroundColor;
    font-size: 1.6rem;
    cursor: move;
    span {
      float: left;
      line-height: 35px;
      margin-left: 15px;
      font-weight: bold;
    }
    .close {
      float: right;
      line-height: 35px;
      margin-right: 8px;
      cursor: pointer;
    }
  }
  ul.base-layer-layers {
    padding: 5px 0;
    margin: 0;
    border-top: 1px solid $borderColor;
    border-bottom: 1px solid $borderColor;
    li {
      list-style: none;
      display: inline-block;
      width: 90px;
      cursor: pointer;
      text-align: center;
      .text {
        width: 100%;
        font-size: 12px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      .layer-status {
        border: 2px solid $borderColorActive;
      }
      .text-status {
        color: $borderColorActive;
      }
    }
  }
  .other-title {
    padding: 5px 15px 5px 5px;
    cursor: pointer;
    .other-title-btn {
      float: right;
    }
  }
  .line-top {
    border-top: 1px solid $borderColor;
  }
  // .other-title:hover {
  //   background: $activeColor;
  // }
  .other-layer-layers {
    margin: 0;
    padding: 0;
    max-height: 130px;
    overflow-y: auto;
    li {
      list-style: none;
      color: $fontColorLimit;
      font-size: 13px;
      line-height: 29px;
      padding-left: 10px;
      position: relative;
      cursor: pointer;
      .check-box {
        cursor: pointer;
        margin-right: 40px;
        float: right;
        line-height: 29px;
        position: absolute;
        display: inline-block;
        right: 10px;
        input[type="checkbox"] {
          cursor: pointer;
        }
      }
    }
    li:hover {
      color:$activeColor;
    }
    .is-selected-status {
      color:$activeColor;
    }
  }
}
.data-table{
  z-index: 1000;
  p.title{
    background: none;
    font-size: 13px;
    padding: 0 10px;
    height: auto;
    line-height: 2;
    color: #40a2de;
  }
}
</style>
<style rel='stylesheet' lang='scss'>
@import "../css/rule.scss";
$activeColor: #eaf1fb;
.base-layer {
  .el-slider__bar {
    background: $borderColorActive;
  }
  .el-slider__button-wrapper {
    width: 14px;
    height: 14px;
    top: -6px;
  }
  .el-slider__button {
    width: 14px;
    height: 14px;
  }
  .el-slider__runway {
    margin: 12px 0;
    height: 4px;
  }
  .el-slider__bar {
    height: 4px;
  }
}
#layerControl_zw{
  .el-collapse{
    border-top: 0px solid #EBEEF5;
    border-bottom: 0px solid #EBEEF5;
    .el-collapse-item{
      .el-collapse-item__header{
        padding-left: 10px;
        height: 29px;
        display: inline-block;
        width: 100%;
        line-height: 29px;
        position: relative;
        box-sizing: border-box;
        background:none;
        color:$fontColorLimit;
        border:1px solid $listBorderBottom;
        .check-box{
          margin-right: 40px;
          float: right;
          line-height: 29px;
          cursor: pointer;
          padding: 0 10px;
        }
        .el-collapse-item__arrow{
          float: right;
          line-height: 29px;
          position: absolute;
          right: 70px;
        }
      }
      .el-collapse-item__header.is-active{
        color:$fontColorActive2;
      }
      .el-collapse-item__wrap{
        background:none;
        border-bottom: none;
      }
      .el-collapse-item__content{
        padding-left: 10px;
        input{
          background: none;
          border: 1px solid $borderColorW;
          color: $fontColorLimit;
        }
      }
    }
  }
}
</style>
